﻿#region LGPL License

/*
OpenSearchNet
Copyright (c) 2014, Brad Hards <bradh@frogmouth.net>, All rights reserved.

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library.
*/

#endregion LGPL License

using System;
using System.Collections.Generic;

namespace OpenSearch
{
    /// <summary>
    /// Request factory for creating search queries
    /// </summary>
    public class RequestFactory
    {
        private Osdd.OpenSearchDescriptionDocument osdd = null;
        private List<Template> availableTemplates = new List<Template>();

        /// <summary>
        /// Create a request factory based on the specified OpenSearch Description Document
        /// </summary>
        /// <param name="osddPath">path (including filename) for the Open Search Description Document</param>
        public RequestFactory(string osddPath)
        {
            using (System.IO.FileStream osddStream = new System.IO.FileStream(osddPath, System.IO.FileMode.Open))
            {
                osdd = new Osdd.OpenSearchDescriptionDocument(osddStream);
                foreach (Osdd.Url url in osdd.Urls)
                {
                    availableTemplates.Add(url.Template);
                }
            }
        }

        /// <summary>
        /// Select the best template match for the parameters that have been substituted
        /// </summary>
        /// <returns>URI form of the template, with appropriate substitutions</returns>
        public Uri GetBestTemplateMatch()
        {
            // TODO: this should be smarter about picking a valid template
            return availableTemplates[0].InstantiateTemplate();
        }

        /// <summary>
        /// Substitute the query search term into the templates
        /// </summary>
        /// <param name="queryTerm">query search term to substitute</param>
        public void SubstituteSearchTermInTemplate(string queryTerm)
        {
            foreach (Template template in availableTemplates)
            {
                template.SubstituteSearchTermInTemplate(queryTerm);
            }
        }
    }
}